﻿using UnityEngine;
using System.Collections;

// EventLine으로 부터 받는 이벤트들 처리 //
public partial class PawnManifest {


	//타격 (공격자가 호출)//
	public void hit(System.Object[] objs)
	{
		if(parentPawn.isDamageDelayed)
			return;

		if(parentPawn.isHealCasting) {
			Debug.Log(gameObject.name+"  Heal  "+healPercent);
			foreach(BattlePawn pawn in healTargetList)
				pawn.OnHeal( healPercent);
		}
		else {

			if (0 < objs.Length)
			{
				//EventlineActor act = objs[0] as EventlineActor;
				hitCount++;
//				Debug.Log(gameObject.name+"  Hit  "+hitCount);
				if(hitCount==1)
					FirstHit();

				int finalDamage = damageToTarget;
				int totalHit = 1;
				if(objs.Length>=2) {
					
					string num = objs[1] as string;
					if (null == num || num == "")
					{
//						Debug.Log("hit num blank  force 1");
						num = "1";
					}
					totalHit = int.Parse(num);
					finalDamage = BattleUtil.GetDividedDamage(damageToTarget, hitCount, totalHit);
				}

				PawnManifest targetMani = targetManifest;
				if(isAttackToSupportDef)
					targetMani = supportDefManifest;
				targetMani.OnDamage( finalDamage, hitCount, damageToTarget);
				if(totalHit==hitCount)
					parentPawn.EventLastHit();
			}
			else {
				Debug.Log("Error  hit arg none");
				FirstHit();
			}
		}
	}
	
	//이동//
	public void move(System.Object[] objs)
	{   
		if (1 < objs.Length)
		{
			string dir = objs[0] as string;
			string dur = objs[1] as string;
			float fDuration = float.Parse(dur);
//			Debug.Log(gameObject.name+"   "+dir+"  ********* Move   "+dur);
			if(dir=="f") {
				isMovedForward=true;
				if(isSupportDefMove || isAttackToSupportDef) {//원호 방어 발생시 상황일때
					Quaternion quat = Quaternion.LookRotation( vReserve1 - transform.position);//이동할 지점을 바라봄//
					if(quat.IsValid())
						transform.rotation = quat;
					LeanTween.move(gameObject, supportDefPos, fDuration).setEase(charInfo.moveForwardTween);

					if(isAttackToSupportDef )
						CamAtkFocus(true);

				}
				else {
					if(isSupportAtkMove && charInfo.isCaster)//원호 공격이고 캐스터 계열일때 앞으로 약간 이동
						LeanTween.move(gameObject, BattleUtil.GetPosToTarget(transform.position, targetManifest.transform.position, charInfo.supportAtkPosOffset), fDuration).setEase(charInfo.moveForwardTween);
					else {
						if(!isSupportAtkMove && parentPawn.IsCurActionPawn() )
						{
							//Debug.Log("Foward Move CamFocus");
							CamAtkFocus(true);
						}
						LeanTween.move(gameObject, BattleUtil.GetTargetAttackPos(transform.position, targetManifest.transform.position, charInfo.myRadius + targetManifest.charInfo.myRadius), fDuration).setEase(charInfo.moveForwardTween);
					}
				}
			}
			else {//dir=="b"
				if(isSupportDefMove) {
					BattleUIManager.Instance.playerExpHUDImage[parentPawn.mNo-1].GetComponent<UIFollowTarget>().enabled = false;
					StopCoroutine("CoGuardLookatEnemy");
				}

				CamAtkFocus(false);
				isMovedForward=false;
				LeanTween.move(gameObject, originalPos, fDuration).setEase(charInfo.moveBackTween);
				if(isSupportDefMove)
					GotoOriginalRot(fDuration);
				
			}
		}
	}

	//원호 공격 발동
	public void supportatk(System.Object[] objs)
	{
		if(charInfo.isCaster )
			return;
		CheckSupportAttack();
	}

	//원호 방어 발동
	public void supportdef(System.Object[] objs)
	{
		if(charInfo.isCaster )
			return;
		CheckSupportDef();
	}

	//원호 방어 가드 액션시//
	public void guard(System.Object[] objs)
	{
		Debug.Log("guard");
		//transform.forward = (targetManifest.originalPos - transform.position).normalized;
		//transform.LookAt( targetManifest.originalPos);
		StartCoroutine("CoGuardLookatEnemy");

		//BattleUtil.LookAt(manifest.transform, manifest.targetManifest.transform);
		if(targetManifest.isMovedForward)//앞으로 이동한 공격자를 살짝 밀어내면서 방어//
		{
			Vector3 vDir = transform.forward;//(manifest.targetManifest.transform.position - transform.position).normalized;
			Vector3 vResult = targetManifest.transform.position + vDir * (charInfo.myRadius + targetManifest.charInfo.myRadius);
			LeanTween.move ( gameObject, targetManifest.transform.position, 0.1f);
			LeanTween.move ( targetManifest.gameObject, vResult, 0.1f);
		}
		parentPawn.OnGuard( targetManifest.damageToTarget);
	}

	//이상하게 자꾸 rotation값이 원래대로 돌아가버려서 계속 강제세팅하도록//
	IEnumerator CoGuardLookatEnemy()
	{
		float sumTime=0;
		while(true) {
			sumTime += Time.deltaTime;
			Quaternion quat = Quaternion.LookRotation( targetManifest.originalPos - transform.position);
			if(quat.IsValid())
				transform.rotation = quat;
			//if(sumTime > 0.1f)
			//	break;
			yield return null;
		}
	}

	//투사체 발사 시점
	public void cast(System.Object[] objs)
	{
		if(charInfo.isCaster )
		{
			GameObject go = Instantiate( BattleResManager.Instance.projectileResDic[parentPawn.myModel.ToString()].projectile) as GameObject;
			go.transform.parent = castPointTrans;//manifest.charInfo.projectileInfo.castBoneTransform;
			BattleUtil.ClearTransformLocal(go.transform);
			go.transform.parent = null;
			go.SetActive(true);
			go.transform.rotation = Quaternion.identity;
			projectile = go.AddComponent<BProjectile>();
			projectile.hitFXPrefab = BattleResManager.Instance.projectileResDic[parentPawn.myModel.ToString()].hit;
			projectile.info = charInfo.projectileInfo;
			Vector3 targetPos = Vector3.zero;
			if(targetManifest.damagePointTrans == null) {
				targetPos = targetManifest.transform.position;
				if(isAttackToSupportDef)
					targetPos = supportDefPos;
				targetPos.y+= 1;
			}
			else {
				targetPos = targetManifest.damagePointTrans.TransformPoint(targetManifest.damagePointTrans.localPosition);
				if(isAttackToSupportDef) {
					float saveY = targetPos.y;
					targetPos = supportDefPos;
					targetPos.y = saveY;
				}
			}
			if(targetPos != Vector3.zero)
				go.transform.LookAt(targetPos);
			float duration;
			if(isAttackToSupportDef)
				duration = projectile.MoveToTarget(this, supportDefManifest, targetPos);
			else
				duration = projectile.MoveToTarget(this, targetManifest ,targetPos);
			parentPawn.addDelayAfterTurn += duration;
			CamAtkFocus(true);
		}
	}

	public void cameraidle(System.Object[] objs)
	{
		Debug.Log("camera idle");
		if(BattleManager.Instance.bUseCamtakeSetting)
			BattleManager.Instance.camtakeSet.idleCamEnterTimeTmp = BattleManager.Instance.camtakeSet.interpolateTime;
		else
			BattleManager.Instance.idleCamEnterTimeTmp=BattleManager.Instance.idleCamInterpolTime;
		BattleManager.Instance.SetSkillCamera(false);
	}

	public void cameraidleinstant(System.Object[] objs)
	{
		Debug.Log("camera idle instant");
		if(BattleManager.Instance.bUseCamtakeSetting)
			BattleManager.Instance.camtakeSet.idleCamEnterTimeTmp = 0;
		else
			BattleManager.Instance.idleCamEnterTimeTmp=0.0f;
		BattleManager.Instance.SetSkillCamera(false);
	}

	public void lighttransform_modify(System.Object[] objs)
	{
		Debug.Log("lighttransform_modify");
		BattleManager.Instance.realTimeLightLocalRotation = EventlineStaticActor.RealTimeLight.transform.localRotation;
	}

	public void lighttransform_original(System.Object[] objs)
	{
		Debug.Log("lighttransform_original");
		EventlineStaticActor.RealTimeLight.transform.localRotation = BattleManager.Instance.realTimeLightLocalRotation;
	}

	//카메라 쉐이크 이후 middle카메라 원점으로 돌리기//
	protected void camerashakeclear()
	{
		BattleManager.Instance.cam.middleCam.transform.localPosition = Vector3.zero;
		BattleManager.Instance.cam.middleCam.transform.localRotation = Quaternion.identity;
		BattleManager.Instance.cam.middleCam.transform.localScale = Vector3.one;
	}

	public void EndOfPlay(IEventlinePlayer takePlayer)
	{
		if(takePlayer.IsLooping)
			return;
		GameObject mainActor = (GameObject)takePlayer.MainActor;
//		Debug.Log(" ################ EndOfPlay event   "+manifest.gameObject.name+"    "+takePlayer.Take.Name);


		if(takePlayer.Take == curTake)
		{
			if(eCurTake== ETake.skill01)
				isSkillActionEnd = true;
			if(eCurTake== ETake.enterstage01 || eCurTake== ETake.forward01)
				bEnterStageComplete=true;
			if(eCurTake== ETake.forward01)
				parentPawn.myAction= EBattleAction.Nothing;

			if(eCurTake== ETake.attack01 || eCurTake== ETake.support_attack01 || eCurTake== ETake.skill01 
			   || eCurTake== ETake.damage01 || eCurTake== ETake.enterstage01 || eCurTake== ETake.forward01) 
			{
				PlayIdleDontStopCurTake();
			}
			else if(eCurTake== ETake.support_guard01)
				EventEndSupportGuard();
			else if(eCurTake== ETake.idle02)
				DonePlayIdle2();
			else if(eCurTake== ETake.die01)
				DoneDieTake();

		}
//		char [] seperator = {'/'};
//		string takeNameAll = takePlayer.Take.Name;
//		string [] takeNames = takeNameAll.Split( seperator );
//		if(takeNames.Length>=2) {
//			if(takeNames[1].Equals("skill01") )
//				manifest.isSkillActionEnd = true;
//
//			if(takeNames[1].Equals("attack01") || takeNames[1].Equals("support_attack01") || takeNames[1].Equals("skill01") || takeNames[1].Equals("ultimate01"))
//				manifest.PlayIdle();
//			else if(takeNames[1].Equals("support_guard01") )
//				manifest.EventEndSupportGuard();
//			else if(takeNames[1].Equals("damage01") )
//				manifest.PlayIdle();
//			else if(takeNames[1].Equals("enterstage01") ) {
//				if(manifest.eCurTake== ETake.enterstage01)//enterstage가 늦게끝나서 다른 테이크가 불렸는지 체크
//					manifest.PlayIdle();
//			}
//		}
	}
}
